using System;
using System.Web.Mvc;
using System.Xml;

namespace Plain.Demo.Blog.Web
{
	public class RssResult : ActionResult
	{
		public Feed Feed { get; set; } 
		
		public override void ExecuteResult(ControllerContext context)     
		{
			XmlWriterSettings xmlSettings = new XmlWriterSettings();
            xmlSettings.Indent = true;
            xmlSettings.NewLineHandling = NewLineHandling.Entitize;
			xmlSettings.Encoding = System.Text.Encoding.UTF8;
 			
			context.HttpContext.Response.ContentType = "application/rss+xml";
			
            using (XmlWriter xmlWriter = XmlWriter.Create(context.HttpContext.Response.OutputStream, xmlSettings))
            {
                xmlWriter.WriteStartElement("rss");
                xmlWriter.WriteAttributeString("version", "2.0");
				xmlWriter.WriteAttributeString("xmlns", "blogChannel", null, Feed.Url);
                xmlWriter.WriteStartElement("channel");
 
                xmlWriter.WriteElementString("title", Feed.Title);
                xmlWriter.WriteElementString("link", Feed.Url);
                xmlWriter.WriteElementString("description", Feed.Description);
				xmlWriter.WriteElementString("language", Feed.Language);
 
                foreach(FeedItem item in Feed.Items)
                {
                    xmlWriter.WriteStartElement("item");
                    xmlWriter.WriteElementString("title", item.Title);
					xmlWriter.WriteElementString("link", item.Url);
					xmlWriter.WriteElementString("description", item.Description);
                    xmlWriter.WriteElementString("author", item.Author);
					foreach (string tag in item.Tags) {
						xmlWriter.WriteElementString("category", tag);
					}
					xmlWriter.WriteElementString("pubDate", item.Published.ToLongDateString());
                    xmlWriter.WriteEndElement();
                }
 
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
			}
		}
	}
}